"""
System Log Controller
Handles business logic related to system logs
"""

from app.models.system_log import SystemLog
from app import db
from flask import g
from app.trace_utils import get_request_info

class SystemLogController:
    """Controller for system log operations"""
    
    @staticmethod
    def create_log(trace_module, trace_content, log_level='INFO', user_id=None):
        """
        Create a new system log entry
        """
        # Get trace information from the current request
        request_info = get_request_info()
        trace_id = request_info.get('trace_id', 'NO_TRACE')
        
        log = SystemLog(
            trace_id=trace_id,
            trace_module=trace_module,
            trace_content=trace_content,
            log_level=log_level,
            user_id=user_id,
            ip_address=request_info.get('remote_addr'),
            user_agent=request_info.get('user_agent')
        )
        
        db.session.add(log)
        db.session.commit()
        
        return log
    
    @staticmethod
    def get_logs_by_trace_id(trace_id):
        """
        Retrieve logs by trace ID
        """
        return SystemLog.query.filter_by(trace_id=trace_id).all()
    
    @staticmethod
    def get_logs_by_module(module_name):
        """
        Retrieve logs by module name
        """
        return SystemLog.query.filter_by(trace_module=module_name).all()
    
    @staticmethod
    def get_logs_by_level(log_level):
        """
        Retrieve logs by log level
        """
        return SystemLog.query.filter_by(log_level=log_level).all()
    
    @staticmethod
    def get_logs_by_user(user_id):
        """
        Retrieve logs by user ID
        """
        return SystemLog.query.filter_by(user_id=user_id).all()